﻿using System.Linq;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;

namespace Ebt.Mvvm.Behaviors
{
    /// <summary>
    /// Allows to set properties of embedded <see cref="ScrollViewer"/> element into e.g. <see cref="ListView"/>. 
    /// </summary>
    public static class ScrollBehavior
    {
        #region ViewChanged attached property

        public static readonly DependencyProperty ViewChangedProperty =
            DependencyProperty.RegisterAttached("ViewChanged", typeof (IEventCommand), typeof (ScrollBehavior), new PropertyMetadata(DependencyProperty.UnsetValue, OnViewChangedPropertyChanged));

        public static void SetViewChanged(DependencyObject d, IEventCommand value)
        {
            d.SetValue(ViewChangedProperty, value);
        }

        public static IEventCommand GetViewChanged(DependencyObject d)
        {
            return (IEventCommand) d.GetValue(ViewChangedProperty);
        }

        private static void OnViewChangedPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var scrollViewer = d.GetChildren().OfType<ScrollViewer>().FirstOrDefault();

            if(scrollViewer == null)
                return;

            scrollViewer.ViewChanged -= ScrollViewerOnViewChanged;
            scrollViewer.ViewChanged += ScrollViewerOnViewChanged;
        }

        private static void ScrollViewerOnViewChanged(object sender, ScrollViewerViewChangedEventArgs scrollViewerViewChangedEventArgs)
        {
            var scrollViewer = (ScrollViewer) sender;
            foreach (var parent in scrollViewer.GetDescendants())
            {
                var command = GetViewChanged(parent);
                if(command == null)
                    continue;

                command.Execute(scrollViewerViewChangedEventArgs.IsIntermediate);
                
                break;
            }
        }

        #endregion
    }
}
